package com.mty.security.aspect;

import com.mty.common.util.JWTUtil;
import com.mty.security.annotation.RequiresPermission;
import com.mty.security.exception.PermissionException;
import com.mty.security.utils.WebUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

/**
 * @author ：Teacher马（2508531326@qq.com）
 * @date ：Created in 2022/12/2 16:56
 * @description：切面类
 * @modified By：
 * @version:
 */
@Component
@Aspect
public class PreAuthorizeAspect {
    //切点: 在哪些位置上添加我们的aop切面
    @Pointcut(value = "@annotation(com.mty.security.annotation.RequiresPermission)")
    public void pointcut() {
    }

    //环绕通知
    @Around(value = "pointcut()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) {
        //获取连接点的方法---获取哪些方法使用了RequiresPermissions
        MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
        // //获取方法上的RequiresPermissions
        checkAnnotation(methodSignature.getMethod());
        Object proceed=null;
        try {
            //回调接口方法
            proceed= proceedingJoinPoint.proceed();
        } catch (Throwable e) {
            e.printStackTrace();
        }
          return  proceed;
    }

    private void checkAnnotation(Method method) {
        RequiresPermission annotation = method.getAnnotation(RequiresPermission.class);
        if (annotation != null) {
            //判断当前用户是否具有注解上的权限。
            String value = annotation.value();
            HttpServletRequest request = WebUtils.getRequest();
            String token = request.getHeader("token");
            Map<String, Object> map = JWTUtil.getTokenChaim(token);
            List<String> permissions = (List<String>) map.get("permissions");
            if (!permissions.contains(value)) {
                throw new PermissionException("权限不足");
            }
        }
    }
}
